// 函数组件
import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, Switch, message, InputNumber } from 'antd';
import "../css/TagDialog.less"
import { addTag, modTag } from '../../../../api/operationApi';

// 表格泛型
interface PropsType {
    isModalOpen: boolean
    modStuInfo?: DataType | undefined
    type: string
    currentPage: number
    pageSize: number
    close(): void
    getData(currentPage: number, pageSize: number): void
    data: DataType[]
}

// 数据类型
interface DataType {
    labelId: number,
    labelName: string,
    labelLocation: number,
    labelState: number,
}


// 表单布局
const layout = {
    labelCol: {
        span: 5,
    },
    wrapperCol: {
        span: 16,
    },
};

// 表单验证
const validateMessages = {
    required: '${label}必填',
    types: {
        number: '${label}必须是数值',
    }
};


function TagDialog(props: PropsType) {
    const [form] = Form.useForm();
    const [title, setTitle] = useState<string>('')

    useEffect(() => {
        if (props.type == 'add') {
            setTitle('添加标签')
            form.resetFields()
            form.setFieldsValue({
                labelId: '',
                labelName: '',
                labelLocation: '',
                labelState: false,
            })

        } else if (props.type == 'mod') {
            setTitle('编辑标签')
            //设置字段默认值
            form.setFieldsValue({
                labelId: props.modStuInfo?.labelId,
                labelName: props.modStuInfo?.labelName,
                labelLocation: props.modStuInfo?.labelLocation,
                labelState: props.modStuInfo?.labelState == 0 ? false : true,
            })
        }
    }, [props])


    // 2、点击提交
    const onFinish = async (values: any) => {
        console.log("values", values);
        if (props.type === 'add') {
            // 遍历是否有相同的标签
            let isExist: boolean = false
            try {
                props.data.forEach((item: DataType) => {
                    if (item.labelName == values.labelName) {
                        isExist = true
                        throw ('已存在该标签')
                    }
                })
            } catch (error) {
                console.log('error', error);
            }

            if (isExist) {
                message.warning('已存在该标签')
            } else {
                let res = await addTag({
                    "labelLocation": values.labelLocation,
                    "labelName": values.labelName,
                    "labelState": values.labelState ? 1 : 0
                })
                await props.getData(props.currentPage, props.pageSize)
                message.success('增加成功')
                props.close()
            }

        } else if (props.type === 'mod') {
            let isExist: boolean = false
            try {
                props.data.forEach((item: DataType) => {
                    if (item.labelName == values.labelName && item.labelId != props.modStuInfo?.labelId) {
                        isExist = true
                        throw ('已存在该标签')
                    }
                })
            } catch (error) {
                console.log('error', error);
            }

            if (isExist) {
                message.warning('已存在该标签')
            } else {
                let res = await modTag({
                    "labelId": values.labelId,
                    "labelLocation": values.labelLocation,
                    "labelName": values.labelName,
                    "labelState": values.labelState ? 1 : 0
                })
                await props.getData(props.currentPage, props.pageSize)
                message.success('修改成功')
                props.close()
            }
        }

    };

    // 点击表单取消
    const cancel = () => {
        message.warning('取消操作')
        props.close()
    }
    // 点击叉叉取消
    const handleCancel = () => {
        message.warning('取消操作')
        props.close()
    };

    return (
        <div className='Dialog'>
            <Modal centered={true} forceRender width={560} title={title} open={props.isModalOpen} footer={null} onCancel={handleCancel} >
                <Form
                    {...layout}
                    name="tag-form"
                    onFinish={onFinish}
                    validateMessages={validateMessages}
                    form={form}
                >
                    {
                        props.type == 'mod' ? (
                            <Form.Item
                                name='labelId'
                                label="序号"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                initialValue={props.modStuInfo?.labelId}
                            >
                                <Input disabled />
                            </Form.Item>
                        ) : ''
                    }
                    <Form.Item
                        name='labelName'
                        label="标签"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.labelName}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name='labelLocation'
                        label="位置"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.labelLocation}
                    >
                        <InputNumber placeholder='位置' min={1} max={10}></InputNumber>
                    </Form.Item>

                    <Form.Item
                        name='labelState'
                        label="状态"
                        valuePropName='checked'
                        initialValue={props.modStuInfo?.labelState}
                    >
                        <Switch />
                    </Form.Item>


                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 8,
                        }}
                    >
                        <Button type="primary" htmlType="submit" className='confirm-btn' >确定</Button>
                        <Button type="primary" onClick={cancel} ghost>取消</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default TagDialog